#include <iostream>

using std::cout;
using std::endl;

class Queue
{
public:
    Queue(int size = 10)
    : _front(0)
    , _rear(0)
    , _size(size)
    , _base(new int[_size]())
    {}

    ~Queue()
    {   
        if(_base) 
        {
            delete [] _base;
            _base = nullptr;
        }
    }

    bool empty() const
    {   return _front == _rear;   }

    bool full() const
    {   return _front == (_rear + 1) % _size; }

    void push(int num) {
        if(full()) {
            cout << "Queue is full, cannot push any data" << endl;
        } else {
            _base[_rear++] = num;
            _rear %= _size;
        }
    }

    void pop() {
        if(empty()) {
            cout << "Queue is empty, no more data" << endl;
        } else {
            ++_front;
            _front %= _size;
        }
    }

    //front/back函数使用前要先做判断，有元素时才能正常调用
    int front() const
    {   return _base[_front]; }

    int back() const 
    {   return _base[(_rear - 1 + _size) % _size];}

private:
    //用指针的写法更灵活
    int _front;
    int _rear;
    int _size;
    int * _base;
};

int main()
{
    Queue s(8);//s中默认情况下最多能存放8个元素
    cout << "s是否为空？" << s.empty() << endl;
    s.push(1);
    cout << "s是否为空？" << s.empty() << endl;

    for(int i = 2; i < 12; ++i) {
        s.push(i);
    }
    cout << "s是否已满？" << s.full() << endl;

    s.pop();//_front: 1 队头元素出队
    s.push(8);//_rear:0
              
    cout << "队头元素是：" << s.front() << endl;
    cout << "队尾元素是：" << s.back() << endl;

    while(!s.empty()) {
        cout << s.front() << endl;//先打印队头元素
        s.pop();//队头元素出队
    }
    cout << "s是否已满？" << s.full() << endl;
    cout << "s是否为空？" << s.empty() << endl;

    return 0;
}

